#!/usr/bin/perl
use LWP::Simple;
sub getPatent 
{
	## get the patent number and output dir
	my $outdir = shift;
	my $pnum = shift;
	
	## ensure that all of our arguments were passed in
	if ((not defined $pnum) or (not defined $outdir)) {die "Invalid patent number or directory\n";}
	
	## attempt to retrieve the patent
	my $url = "http://patft.uspto.gov/netacgi/nph-Parser?".
		 "Sect1=PTO1&Sect2=HITOFF&d=PALL&p=1&u=%2Fnetahtml%2FPTO%2Fsrchnum.htm&r=1&f=G&l=50".
		 "&s1=$pnum.PN.&OS=PN/$pnum&RS=PN/$pnum";
	my $content = get $url;
	
	## try again if patent wasn't retrieved the first time
	while (not defined $content)
	{
		print "  !Failed to get patent $pnum.  Trying again...\n";
		$content = get $url;
	}
	#die "Could not retrieve patent ".$pnum if (not defined $conent);
	
	my $filename = $outdir.$pnum.".html";
	open(my $f, ">".$filename) or die "Could not open file $filename\n";
	print $f $content;
	close $f;
	
	print "Wrote patent file: $filename\n";
}

## define boundary variables
my $start = 4e6;
my $count = -1; ## loop indefinitely
my $last = -1;
#my $directory = "patents/";

if((@ARGV > 0) && ((@ARGV[0] == "--help")  || (@ARGV[0] == "-h")))
{
	print "getpatent.pl [start-index] [count] [directory]\n";
	exit;
}

## see whether any of these were passed as command-line arguments, and act accordingly
$start = @ARGV[0] if (@ARGV > 0);
$count = @ARGV[1] if (@ARGV > 1);
if ($count == 0)
{
	print "Got 0 patents\n";
	exit;
}
$last = $start+$count-1 if $count > 0;

my $directory = $start;  ## by default the output directory is the name of the start value
$directory = @ARGV[2] if (@ARGV > 2);
## ensure that our directory ends in a / or \
$directory = $directory."/" if !(($directory =~ m/\/$/) || ($directory =~ m/\$/));
print "Output directory is $directory\n";

## ensures that our directory exists
if(not -d $directory)
{
	mkdir $directory or die $!;
	print "Created directory $directory\n";
}

## get each patent; also, get patents whose files exist but are empty (easy bug fix from old version)
for (my $i = $start; ($i <= $last) || ($last < 0); $i++)
{
	$filename = "$directory$i.html";
	#print "$filename is the filename\n";
	## if the file doesn't exist or exists but has nothing it it, get it
	if (not -e $filename)
	{
		getPatent($directory, $i);
	}
	elsif (-z $filename)
	{
		print "File \"$filename\" found, but contains no data and will be replaced.\n";
		getPatent($directory, $i);
	}
}
